﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace JAMR.Rendering
{
    public class FoliageCache
    {
        // Singleton
        private static FoliageCache _instance = new FoliageCache();

        public static FoliageCache Instance { get { return _instance; } }
        
        // Class
        private FoliageCache() 
        {
            _texes = new Dictionary<string, int>();
        }

        public bool HasImage { get { return _image != null; } }

        private Bitmap _image = null;

        public void SetFoliage(Bitmap image)
        {
            if (image.Width != 256 || image.Height != 256)
                throw new Exception("Foliage image incorrect size");

            _image = image;
        }

        public Color GetColour(int x, int y)
        {
            return _image.GetPixel(x, y);
        }
        public Color GetColour(int id)
        {
            int x, y;
            IdToXy(id, out x, out y);

            return GetColour(x, y);
        }
        
        private int xyToId(int x, int y)
        {
            return y * 256 + x;
        }
        private void IdToXy(int id, out int x, out int y)
        {
            x = id % 256;
            y = (id - x) / 256;
        }

        private IDictionary<string, int> _texes;
        public string GetTexture(string baseTex, int foliageId)
        {
            int x, y;
            IdToXy(foliageId, out x, out y);

            return GetTexture(baseTex, x, y);
        }
        public string GetTexture(string baseTex, int x, int y)
        {
            // Create name
            string name = string.Format("{0}_foliage_{1}_{2}", baseTex, x, y);

            // Exists?
            TextureCache tc = TextureCache.Instance;
            
            if (tc.Contains(name))
                return name;

            // Get foliage
            Color foliage = GetColour(x, y);

            // Create
            Bitmap b = new Bitmap(tc.GetImage(baseTex));

            // Multiply by foliage
            for (int x1 = 0; x1 < b.Width; x1++)
                for (int y1 = 0; y1 < b.Height; y1++)
                {
                    try
                    {
                        Color c = b.GetPixel(x1, y1);
                        Color n = Color.FromArgb(byte.MaxValue, c.R + foliage.R, c.G + foliage.G, c.B + foliage.B);
                        b.SetPixel(x1, y1, n);
                    }
                    catch (Exception)
                    {
                    }
                }

            // Save
            tc.LoadTexture(b, name);

            return name;
        }
    }
}
